﻿Public Partial Class frm_Pre_Booking
    Inherits System.Web.UI.Page

    Dim clsGet As New ClassFunctionGetData
    Dim clsFc As New ClassFunction
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not (IsPostBack) Then
            Dim lbPage As Label = CType(Master.FindControl("lbPage"), Label)
            lbPage.Text = "PRE BOOKING "
            panelDetail.Visible = False
            PanelPre.Visible = True
            'If (CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("Customer_no") & "" <> "") Then
            '    txtid.Text = CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("Customer_no") & "-" & CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("Customer_name")
            'End If
        End If
    End Sub

    Private Sub radioVehicle_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles radioVehicle.SelectedIndexChanged
        If (radioVehicle.SelectedValue = "0") Then
            'In
            txtVessel.Text = txtVesselOUT.Text
            PanelVEHICLE_IN.Visible = True
            PanelVEHICLE_OUT.Visible = False
            lbFT1.Text = "FT"
            lbFT2.Text = "FT"
        Else
            'OUT
            txtVesselOUT.Text = txtVessel.Text
            PanelVEHICLE_IN.Visible = False
            PanelVEHICLE_OUT.Visible = True
            lbFT1.Text = "M"
            lbFT2.Text = "M"
        End If
    End Sub

    Private Sub btnSaveProduct_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSaveProduct.Click
        Dim dt As DataTable = Session("Product_popup")
        If (dt.Rows.Count > 0) Then
            If (txtid.Text.Trim() <> "") Then
                Dim name() As String = txtid.Text.Split("-")
                Dim soldto As String = txtid.Text.Split("-")(0) & "฿"
                For i As Integer = 1 To name.Length - 1
                    soldto &= name(i) & " "
                Next
                ViewState("OwnerColumn") = soldto
            Else
                ViewState("OwnerColumn") = "฿Sold To"
            End If
            If (dt.Rows(0).Item("Product_Event") & "" = "L") Or (dt.Rows(0).Item("Product_Event") & "" = "R") Then
                lbType.Text = "DISCHARGING PORT"
                gridProduct.Columns(8).HeaderText = "DISCHARGING PORT"
            Else
                lbType.Text = "LOADING PORT"
                gridProduct.Columns(8).HeaderText = "LOADING PORT"
            End If
        End If
        gridProduct.DataSource = dt
        gridProduct.DataBind()
    End Sub

    Private Sub gridProduct_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gridProduct.RowCommand
        Dim Index As Integer = Convert.ToInt32(e.CommandArgument)
        If e.CommandName = "cmddelete" Then
            Dim ds As DataTable = Session("Product_popup")
            ds.Rows(Index).Delete()
            ds.AcceptChanges()
            If (ds.Rows.Count = 0) Then
                ds = CreateDatasetProduct()
            End If
            Session("Product_popup") = ds
            gridProduct.PageIndex = 0
            gridProduct.DataSource = Session("Product_popup")
            gridProduct.DataBind()
        ElseIf e.CommandName = "cmdedit" Then
            Session("IndexProduct") = Index
            Session("PORT_PRODUCT") = radioPort.SelectedValue
            ModalPopupExtender5.Show()
        End If
    End Sub

    Private Sub gridProduct_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridProduct.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim ImgDelete As ImageButton = CType(e.Row.FindControl("imgdelete"), ImageButton)
            Dim ImgEdit As ImageButton = CType(e.Row.FindControl("imgedit"), ImageButton)
            If (gridProduct.DataKeys(e.Row.RowIndex).Values("Product_name") & "" = "") Then
                ImgDelete.Visible = False
                ImgEdit.Visible = False
            End If
            If (gridProduct.DataKeys(e.Row.RowIndex).Values("Product_Event") & "" = "L") Then
                e.Row.Cells(0).Text = "Load"
            ElseIf (gridProduct.DataKeys(e.Row.RowIndex).Values("Product_Event") & "" = "D") Then
                e.Row.Cells(0).Text = "Disch"
            ElseIf (gridProduct.DataKeys(e.Row.RowIndex).Values("Product_Event") & "" = "R") Then
                e.Row.Cells(0).Text = "Load(IRPC)"
            ElseIf (gridProduct.DataKeys(e.Row.RowIndex).Values("Product_Event") & "" = "I") Then
                e.Row.Cells(0).Text = "Disch(IRPC)"
            End If
            If (gridProduct.DataKeys(e.Row.RowIndex).Values("Group_no") & "" = "0000000000") Then
                e.Row.BackColor = Drawing.Color.Red
            End If
        End If
    End Sub

    Private Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        Try
            If (radioPort.SelectedValue = "") Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการเลือกท่าเรือ !!');", True)
                Exit Sub
            End If
            If Not (txtVessel.Text.Trim() = "") Then
                Dim ds As DataTable = clsGet.Get_VEHICLE_DETAIL(txtVessel.Text.Split("-")(0))
                If (ds.Rows.Count > 0) Then
                    'พบเรือ
                    'Update Vessel
                    ds = clsGet.Get_VEHICLE_DETAIL(txtVessel.Text.Split("-")(0))
                    txtVessel.Enabled = False
                    txtid.Enabled = False
                    radioVehicle.Enabled = False
                    btnSearch.Visible = False
                    radioPort.Enabled = False
                    'Bind Data VEHICLE Detail
                    lbLOA.Text = (CDbl(ds.Rows(0).Item("VEH_LENGTH")) * 3.281).ToString("############0.00")
                    lbDWT.Text = ds.Rows(0).Item("VEH_MAXWGT_C").ToString().Trim()
                    lbDraft.Text = (CDbl(ds.Rows(0).Item("DRAFT")) * 3.281).ToString("############0.00")
                    lbNation.Text = ds.Rows(0).Item("REG_CNTRY")
                    If Not ((ds.Rows(0).Item("STCMNR") & "").ToString().Trim() = "") Then
                        Try
                            lbGRT.Text = ds.Rows(0).Item("STCMNR").ToString().Replace("GRT", "").Replace("=", "").Replace("MT", "")
                        Catch ex As Exception

                        End Try
                    End If
                    PanelVEHICLE_IN_DETAIL.Visible = True
                    panelProductDetail.Visible = True
                    Session("Product_popup") = CreateDatasetProduct()
                    gridProduct.DataSource = Session("Product_popup")
                    gridProduct.DataBind()
                Else
                    'ไม่พบเรือ
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ข้อมูลเรือไม่ถูกต้อง!!');", True)
                End If
            Else
                'ยังไม่ระบุข้อมูลเรือ
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุเรือ!!');", True)
            End If

        Catch ex As Exception
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่สามารถทำการเชื่อมต่อ SAP ได้!!');", True)
        End Try
    End Sub

    Private Sub btnSearchOUT_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearchOUT.Click
        If Not (txtVesselOUT.Text.Trim() = "") Then
            If (txtGRT.Text.Trim() = "") Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุ GRT!!');", True)
                Exit Sub
            End If
            If (txtDraft.Text.Trim() = "") Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุ Draft!!');", True)
                Exit Sub
            End If
            If (txtDWT.Text.Trim() = "") Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุ DWT!!');", True)
                Exit Sub
            End If
            If (txtLOA.Text.Trim() = "") Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุ LOA!!');", True)
                Exit Sub
            End If
            txtVesselOUT.Enabled = False
            radioVehicle.Enabled = False
            txtLOA.Enabled = False
            txtDWT.Enabled = False
            txtDraft.Enabled = False
            txtGRT.Enabled = False
            txtid.Enabled = False
            ddlNation.Enabled = False
            btnSearchOUT.Visible = False
            radioPort.Enabled = False
            panelProductDetail.Visible = True
            Session("Product_popup") = CreateDatasetProduct()
            gridProduct.DataSource = Session("Product_popup")
            gridProduct.DataBind()
            '  LoadDefault_MAT(ddlNation.SelectedValue)
        Else
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุเรือ!!');", True)
        End If
    End Sub

    Public Function CreateDatasetProduct() As DataTable
        Dim ds As New DataSet
        Dim dt As New DataTable
        Dim dr As DataRow
        ds.Tables.Add(dt)
        dt.Columns.Add("Product_no", GetType(String))
        dt.Columns.Add("Product_name", GetType(String))
        dt.Columns.Add("Product_Amount", GetType(String))
        dt.Columns.Add("Product_Event", GetType(String))
        dt.Columns.Add("Product_Description", GetType(String))
        dt.Columns.Add("Product_Unit", GetType(String))
        dt.Columns.Add("Group_name", GetType(String))
        dt.Columns.Add("Group_no", GetType(String))
        dt.Columns.Add("Product_BUYER_no", GetType(String))
        dt.Columns.Add("Product_BUYER_name", GetType(String))
        dt.Columns.Add("Product_SELLER_no", GetType(String))
        dt.Columns.Add("Product_SELLER_name", GetType(String))
        dt.Columns.Add("LoadDestination", GetType(String))
        dt.Columns.Add("DischDestination", GetType(String))
        dt.Columns.Add("DestinationShow", GetType(String))
        dt.Columns.Add("Owner_Product_no", GetType(String))
        dt.Columns.Add("Owner_Product_name", GetType(String))
        dr = ds.Tables(0).NewRow
        dr.Item("Product_no") = ""
        dr.Item("Product_name") = ""
        dr.Item("Product_Amount") = ""
        dr.Item("Product_Event") = ""
        dr.Item("Product_Description") = ""
        dr.Item("Product_Unit") = ""
        dr.Item("Group_name") = ""
        dr.Item("Group_no") = ""
        dr.Item("Product_BUYER_no") = ""
        dr.Item("Product_BUYER_name") = ""
        dr.Item("Product_SELLER_no") = ""
        dr.Item("Product_SELLER_name") = ""
        dr.Item("LoadDestination") = ""
        dr.Item("DischDestination") = ""
        dr.Item("DestinationShow") = ""
        dr.Item("Owner_Product_no") = ""
        dr.Item("Owner_Product_name") = ""
        ds.Tables(0).Rows.Add(dr)
        ds.Tables(0).AcceptChanges()
        Return ds.Tables(0)
    End Function

    Private Sub btnProduct_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnProduct.Click
        Session("PORT_PRODUCT") = radioPort.SelectedValue
        ModalPopupExtender5.Show()
    End Sub

    Public Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Response.Redirect("../Form/Simulate_Booking.aspx?P4=B", True)
    End Sub

    Private Sub btnCompute_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCompute.Click
        If (txtDate.Text.Trim = "") Or (txtDateTo.Text.Trim = "") Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุ Lay Can/Lay Day!!');", True)
            Exit Sub
        End If

        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
        Dim clsDB As New ClassDatabase
        Dim condition As Boolean = True
        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
        Dim Vehicle As String = ""
        Dim Vehicle_Name As String = ""
        Dim LOA As String = ""
        Dim DWT As String = ""
        Dim Draft As String = ""
        Dim GRT As String = ""
        Dim CNTRY As String = ""
        Dim Booking As String = ""
        Dim Vehicle_TypeBuy As String = ""
        If (ViewState("EditBooking") & "" = "") Then
            Dim Pre_Booking As String = clsDB.GeneratorID(conn, "Pre_Booking")
            Booking = clsDB.GeneratorID(conn, "Booking")
            If (CInt(Pre_Booking) > CInt(Booking)) Then
                Booking = Pre_Booking
            End If
        Else
            Booking = ViewState("EditBooking")
        End If
        If (radioVehicle.SelectedValue = "0") Then
            Vehicle = txtVessel.Text.Split("-")(0)
            '  Vehicle_Name = txtVessel.Text.Split("-")(1)
            Dim AgentLoops() As String = txtVessel.Text.Split("-")
            For i As Integer = 0 To AgentLoops.Length - 1
                If (i <> 0) Then
                    Vehicle_Name &= "-" & AgentLoops(i).ToString()
                End If
            Next
            Vehicle_Name = Vehicle_Name.Substring(1, Vehicle_Name.Length - 1)
            LOA = lbLOA.Text.Trim()
            DWT = lbDWT.Text.Trim()
            Draft = lbDraft.Text.Trim()
            GRT = lbGRT.Text.Trim()
            CNTRY = lbNation.Text.Trim()
        Else
            Vehicle = "999999999"
            Vehicle_Name = txtVesselOUT.Text.Trim()
            LOA = txtLOA.Text.Trim()
            DWT = txtDWT.Text.Trim()
            Draft = txtDraft.Text.Trim()
            GRT = txtGRT.Text.Trim()
            CNTRY = ddlNation.SelectedValue.Replace("T", "TH")
        End If
        If (raioType.SelectedValue = "O") Then
            Vehicle_TypeBuy = radioTypeBuy.SelectedValue
        End If
        Dim MAgent_no As String = ""
        Dim MAgent_name As String = ""
        If (txtid.Text.Trim = "") Then
            MAgent_no = ""
            MAgent_name = ""
        Else
            MAgent_no = txtid.Text.Split("-")(0)
            ' MAgent_name = txtid.Text.Split("-")(1)
            Dim AgentLoops() As String = txtid.Text.Split("-")
            For i As Integer = 0 To AgentLoops.Length - 1
                If (i <> 0) Then
                    MAgent_name &= "-" & AgentLoops(i).ToString()
                End If
            Next
            MAgent_name = MAgent_name.Substring(1, MAgent_name.Length - 1)
        End If
        Application.Lock()
        conn.Open()
        tran = clsDB.BeginTran(conn)
        Try
            If (clsFc.InsertPre_Booking(ViewState("EditBooking"), Booking, CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name"), CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("Name"), Vehicle, Vehicle_Name, LOA, DWT, Draft, GRT, txtDate.Text, txtDateTo.Text, radioPort.SelectedValue, raioType.SelectedValue, Vehicle_TypeBuy, txtRemark.Text, "N", MAgent_no, MAgent_name, CNTRY, txtWater.Text.Trim(), txtElectricity.Text, "", "", "", "", "", "", "", "", "", "", "", "", conn, tran) > 0) Then
                Dim dsProduct As DataTable = Session("Product_popup")
                clsFc.DeleteBookingProduct(Booking, conn, tran)
                For Each dr As DataRow In dsProduct.Rows
                    If (dr.Item("Product_no") & "" <> "") Then
                        Dim Destination As String = ""
                        If (dr.Item("Product_Event") = "L") Or (dr.Item("Product_Event") = "R") Then
                            Destination = dr.Item("LoadDestination")
                        Else
                            Destination = dr.Item("DischDestination")
                        End If
                        If (clsFc.InsertBooking_Product("", Booking, dr.Item("Product_no"), dr.Item("Product_name"), dr.Item("Product_Amount"), dr.Item("Product_Event"), dr.Item("Group_no"), dr.Item("Group_name"), dr.Item("Product_Buyer_no"), dr.Item("Product_Buyer_name"), dr.Item("Product_Seller_no"), dr.Item("Product_Seller_name"), dr.Item("LoadDestination"), dr.Item("DischDestination"), dr.Item("DestinationShow"), dr.Item("Product_Description"), dr.Item("Product_Unit"), dr.Item("Owner_Product_no"), dr.Item("Owner_Product_name"), conn, tran) < 1) Then
                            condition = False
                            Exit For
                        End If
                    End If

                Next
            Else
                condition = False
            End If
            If (condition) Then
                clsDB.CommitTran(tran)
                ViewState("EditBooking") = ""
                Session("Product_popup") = CreateDatasetProduct()
                panelDetail.Visible = True
                PanelPre.Visible = False
                lbBookingNo.Text = Booking
                lbVESSELDetail.Text = Vehicle_Name
                lbLayCan.Text = txtDate.Text & " - " & txtDateTo.Text
                lbSoldTo.Text = txtid.Text
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('บันทึกข้อมูลสำเร็จ !!');", True)
            Else
                clsDB.RollBackTran(tran)
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก !!');", True)
            End If
        Catch ex As Exception
            clsDB.RollBackTran(tran)
            txtRemark.Text = ex.Message
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก  !!');", True)
        End Try
        Application.UnLock()
        conn.Dispose()

    End Sub


    Private Sub raioType_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles raioType.SelectedIndexChanged
        If raioType.SelectedValue = "O" Then
            rowTypeBuy.Visible = True
        Else
            rowTypeBuy.Visible = False
        End If
    End Sub


    Private Sub MainPage_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
        Dim ds As DataSet = Session("UserData")
        If Not (ds Is Nothing) Then
            Page.MasterPageFile = clsGet.GetMaster_Page(ds.Tables(0).Rows(0).Item("User_Name").ToString(), "M")
        End If
    End Sub
End Class